import dayjs from 'dayjs';
import { readBody } from 'h3';
import { md5 } from '~/server/utils/util.crypto';
import { AdminModel } from '~/server/models/admin.model';

// 修改密码接口
export default defineEventHandler(async (event): Promise<any> => {
	try {
		const body = await readBody(event);

		const { _id, oldPassword, newPassword } = body;

		if (!_id || !oldPassword || !newPassword) return { code: 0, message: '参数不完整' };

		const user = await AdminModel.findById(_id);

		if (!user) return { code: 0, message: '用户不存在' };

		if (user.password !== sha256(md5(oldPassword))) return { code: 0, message: '原密码错误' };

		user.password = sha256(md5(newPassword));

		user.updatedAt = dayjs().format('YYYY年MM月DD日 HH:mm:ss');

		await user.save();

		return { code: 1, message: '密码修改成功' };
	} catch (error: any) {
		return { code: 0, message: error.message };
	}
});
